package com.zhongfl.crm.lixiao.batch.service;

import com.heptagram.lixiao.api.LiXiaoService;
import com.heptagram.lixiao.bean.LiXiaoConsts;
import com.heptagram.lixiao.bean.enums.ContractStatus;
import com.heptagram.lixiao.bean.enums.OpportunityStage;
import com.heptagram.lixiao.bean.request.contract.LXContractInfo;
import com.heptagram.lixiao.bean.request.contract.LXContractSaveRequest;
import com.heptagram.lixiao.bean.request.opportunity.LXOpportunity;
import com.heptagram.lixiao.bean.request.opportunity.LXOpportunityRequest;
import com.heptagram.lixiao.bean.response.contract.LXContractSaveResponse;
import com.heptagram.lixiao.common.exception.LiXiaoErrorException;
import com.zhongfl.crm.exception.CRMException;
import com.zhongfl.crm.lixiao.common.LxStatusConvertUtils;
import com.zhongfl.crm.lixiao.mapper.LXOrderMapper;
import com.zhongfl.crm.model.LxUser;
import com.zhongfl.crm.model.boss.LxOrder;
import com.zhongfl.crm.model.boss.Order;
import com.zhongfl.crm.model.boss.OrderCreatedMessage;
import com.zhongfl.crm.service.LxUserService;
import com.zhongfl.crm.service.boss.LXOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import tech.heptagram.channel.api.model.Channel;
import tech.heptagram.channel.api.service.ChannelService;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Objects;

/**
 * 励销订单创建服务
 *
 * @author wang.yuchuan
 * @date 2018/8/27
 */
@Service
@Slf4j
public class LxDeliverOrderCreateService {

    @Resource
    private LiXiaoService liXiaoService;

    @Resource
    private LXOrderService lxOrderService;

    @Resource
    private ChannelService channelService;

    @Resource
    private LxUserService lxUserService;

    @Resource
    private LXOrderMapper lxOrderMapper;

    public static final int SAVE_SUCCESSED_CODE = 0;

    public static final String DELIVER_ORDER_TYPE = "contract";

    /**
     * 创建励销交付订单
     *
     * @param orderCreatedMessage BOSS交付订单创建消息
     */
    public void createLiXiaoDeliverOrder(OrderCreatedMessage orderCreatedMessage) throws LiXiaoErrorException {

        Order deliverOrder = lxOrderService.findByOrderNo(orderCreatedMessage.getOrderNo());

        log.info("开始同步客户订单:{} 的交付订单到励销", deliverOrder.getName());

        // 1. 构造要创建的励销交付订单参数
        LXContractSaveRequest contractSaveRequest = buildContractSaveRequest(deliverOrder, orderCreatedMessage.getLxId());

        // 2. 调用励销接口,创建交付订单
        LXContractSaveResponse saveContractResult = liXiaoService.getContractService().createContract(contractSaveRequest);


        if (saveContractResult.getCode() == SAVE_SUCCESSED_CODE) {
            Long lxContractId = saveContractResult.getData().getId();

            // 3. 创建励销交付订单成功, 保存励销交付订单关系到lx_order
            log.info("保存交付订单同步记录开始：", deliverOrder.getName(), deliverOrder.getOrderNo());
            LxOrder lxOrderSaveInfo = buildLXOrderForContract(deliverOrder, lxContractId);
            lxOrderMapper.insertSelective(lxOrderSaveInfo);
            log.info("保存交付订单同步记录完成！", deliverOrder.getName(), deliverOrder.getOrderNo());

            // 4. 更新boss交付订单表lx_deliver_order_id字段
            lxOrderService.updateLxDeliverOrderId(deliverOrder.getOrderNo(), lxContractId);
        }

        // 5. 励销客户订单状态更新为采集库
        log.info("开始将励销的商机'赢单'状态还原为'采集库'");
        LXOpportunityRequest request = buildLxOpportunityUpdateRequest(orderCreatedMessage, deliverOrder);
        liXiaoService.getOpportunityService().updateOpportunity(request);
        log.info("还原商机状态成功");

        log.info("同步交付订单到励销完成");
    }

    /**
     * 构建励销客户订单状态变更参数对象
     *
     * @param orderCreatedMessage boss交付订单创建消息对象
     * @param deliverOrder        boss交付订单消息
     * @return
     */
    private LXOpportunityRequest buildLxOpportunityUpdateRequest(OrderCreatedMessage orderCreatedMessage, Order deliverOrder) {
        LXOpportunity lxOpportunity = new LXOpportunity();
        lxOpportunity.setId(orderCreatedMessage.getLxId());
        lxOpportunity.setTitle(deliverOrder.getName());
        lxOpportunity.setStage(String.valueOf(OpportunityStage.STATUS_COLLECT.getId()));
        //这里应该更新下励销客户订单的订单号，但是没有这个字段

        Channel channel = channelService.findById(deliverOrder.getChannelId());
        if (Objects.nonNull(channel)) {
            lxOpportunity.setCustomerId(channel.getLxCustomerId());
        }

        LXOpportunityRequest request = new LXOpportunityRequest();
        request.setOpportunity(lxOpportunity);
        request.setId(lxOpportunity.getId());
        return request;
    }

    /**
     * 构建励销交付订单创建参数对象
     *
     * @param order           boss交付订单对象
     * @param lxOpportunityId 励销客户订单ID
     * @return 励销保存结果
     */
    private LXContractSaveRequest buildContractSaveRequest(Order order, Long lxOpportunityId) {
        LXContractInfo saveContract = new LXContractInfo();

        saveContract.setOpportunityId(lxOpportunityId);
        saveContract.setTitle(order.getName());

        Channel channel = channelService.findById(order.getChannelId());
        saveContract.setCustomerId(channel.getLxCustomerId());
        //修改一：状态改为已审批
        saveContract.setApproveStatus(LiXiaoConsts.ContractApprovalStatus.APPROVED);
        saveContract.setContractActionName(LiXiaoConsts.TURN_TO_CONTRACT);
        saveContract.setSn(order.getOrderNo());
        //修改二：合同状态改成和订单一样
        ContractStatus contractStatus = LxStatusConvertUtils.convertDeliverOrderStatus2LxContractStage(order.getStatus());
        if (Objects.nonNull(contractStatus)) {
            saveContract.setStatus(String.valueOf(contractStatus.getId()));
        } else {
            throw new CRMException("励销合同状态没有对应当前订单的状态，当前订单号：" + order.getOrderNo());
        }

        saveContract.setTotalAmount(order.getLoanAmount().multiply(new BigDecimal(10000)));
        //修改三：添加贷款年限
        saveContract.setNumericAsset_Ffae20(order.getLoanDuration());

        // todo 这里的负责人应改为交付的巴员为负责人，但是现在没有分配，暂时用商务经理
        LxUser lxUser = lxUserService.findByStaffCode(order.getBusinessManagerStaffCode());
        saveContract.setUserId(lxUser.getLxId());

        LXContractSaveRequest request = new LXContractSaveRequest();
        request.setContract(saveContract);

        return request;
    }

    private LxOrder buildLXOrderForContract(Order order, Long lxContractId) {
        LxOrder lxOrder = new LxOrder();
        lxOrder.setLxId(lxContractId);
        lxOrder.setOrderType(DELIVER_ORDER_TYPE);
        lxOrder.setLxContractId(lxContractId);
        lxOrder.setTitle(order.getName());
        Channel channel = channelService.findById(order.getChannelId());
        lxOrder.setCustomerId(channel.getLxCustomerId());
        lxOrder.setCustomerName(channel.getChannelName());

        lxOrder.setLxOrderAmount(order.getLoanAmount());
        LxUser lxUser = lxUserService.findByStaffCode(order.getBusinessManagerStaffCode());
        lxOrder.setLxUserId(lxUser.getLxId());
        lxOrder.setOrderNo(order.getOrderNo());

        lxOrder.setCreatedBy("system");
        lxOrder.setModifiedBy("system");

        return lxOrder;
    }
}
